#include "Cpu.h"
#include "pin_mux.h"
#include "dmaController1.h"
#include "clockMan1.h"
#include "lpuart1.h"
#include "uart_drv.h"
#include "TPS929120A.h"
#include "string.h"
#include "userdefine.h"

uint16_t receiveByteNum = 0;
uint16_t timeOutFlag = 0;

/* UART rx callback for continuous reception, byte by byte */
void rxCallback(void *driverState, uart_event_t event, void *userData)
{
    /* Unused parameters */
    (void)driverState;
    (void)userData;

    /* Check the event type */
    if (event == UART_EVENT_RX_FULL)
    {
        timeOutFlag = 1;
        /* Update the buffer index and the rx buffer */
    	receiveByteNum++;
    	LPUART_DRV_SetRxBuffer(INST_LPUART1, &g_rcvBuffer[receiveByteNum], 1U);
    }
}

void Uart_Init(void)
{
    /* Initialize LPUART instance */
    LPUART_DRV_Init(INST_LPUART1, &lpuart1_State, &lpuart1_InitConfig0);
    LPUART_DRV_InstallRxCallback(INST_LPUART1, rxCallback, NULL);
}

void uart_task(void)
{
    /* Write your local variable definition here */
    status_t status;
    /* Declare a buffer used to store the received data */
    uint32_t bytesRemaining;
      
    /* Wait for transfer to be completed */
    while(LPUART_DRV_GetReceiveStatus(INST_LPUART1, &bytesRemaining) == STATUS_BUSY);

    /* Check the status */
    status = LPUART_DRV_GetReceiveStatus(INST_LPUART1, &bytesRemaining);

    // if (status != STATUS_SUCCESS)
    // {
    //     /* If an error occurred, send the error message and exit the loop */
    //     LPUART_DRV_SendDataBlocking(INST_LPUART1, (uint16_t *)errorMsg, strlen(errorMsg), TIMEOUT);
    // }

    /* Send the received data back */
    // LPUART_DRV_SendDataBlocking(INST_LPUART1, buffer, bufferIdx, TIMEOUT);
    /* Reset the buffer index to start a new reception */
}


void Transfer(uint32_t txbuffer_size, uint32_t rxbuffer_size, uint16_t response_enabled)
{
    status_t status;
    uint32_t bytesRemaining;

    LPUART_DRV_SendData(INST_LPUART1, g_sendBuffer, txbuffer_size);
    // LPUART_DRV_ReceiveData(INST_LPUART1, g_rcvBuffer, rxbuffer_size);
    // while(LPUART_DRV_GetReceiveStatus(INST_LPUART1, &bytesRemaining) == STATUS_BUSY);

    if (response_enabled == TRUE)
    {
        LPUART_DRV_ReceiveData(INST_LPUART1, g_rcvBuffer, rxbuffer_size);
        // while(LPUART_DRV_GetReceiveStatus(INST_LPUART1, &bytesRemaining) == STATUS_BUSY);
        // status = LPUART_DRV_GetReceiveStatus(INST_LPUART1, &bytesRemaining);

        // if(status != STATUS_SUCCESS)
        // {
        //     //接收失败
        // }
        // else
        // {
        //     //接收成功
        // }

    }
    else
    {
        // while(LPUART_DRV_GetTransmitStatus(INST_LPUART1, &bytesRemaining) == STATUS_BUSY);
        // status = LPUART_DRV_GetTransmitStatus(INST_LPUART1, &bytesRemaining);
        
        // if(status != STATUS_SUCCESS)
        // {
        //     //发送失败
        // }
        // else
        // {
        //     //发送成功
        // }

    }
}